package com.lagou.boot;

import com.lagou.client.RPCConsumer;
import com.lagou.service.IUserService;
import com.lagou.zk.CommonNode;
import com.lagou.zk.ZookeeperClient;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class ConsumerBoot implements ApplicationRunner {

    @Autowired
    private RPCConsumer rpcConsumer;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 添加监听
        PathChildrenCache childrenCache = new PathChildrenCache(ZookeeperClient.getClient(), CommonNode.serverNode, true);
        childrenCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
        childrenCache.getListenable().addListener(rpcConsumer);

        // 初始化客户端
        rpcConsumer.initClient();
        try {
            //2.循环给服务器写数据
            while (true){
                // 获取代理对象
                IUserService service = (IUserService) rpcConsumer.getProxy(IUserService.class);
                String result = service.sayHello("Hello Provider~！");
                System.out.println(result);
                Thread.sleep(2000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
